<script setup lang="ts">
import type { TreeNodeData } from '@/components/ApplicationModelTree'
import { useTemplateView } from '@/mixins/MixinTemplateView'
import { STORAGE_MODES_OPTIONS } from '@/mixins/StatisticalIndicators/MixinStatisticalIndicators'
import { STORAGE_MODES } from '@/enum/modules/indicator'
import type { DatePickType } from 'element-plus'
import useTemplateData, { setCacheModelId } from './composable'
import IndicatorDataCurveModal from '@/components/IndicatorDataCurveModal/IndicatorDataCurveModal.vue'
import { exportData2 as exportData } from '@/api/modules/template'

defineOptions({ name: 'Template002' })

const { getCode } = useTemplateView()
const [current, setCurrent] = useState<TreeNodeData | null>(null)
const code = getCode()

const timeType = ref(STORAGE_MODES.HOUR)
const startTime = ref(dayjs().subtract(24, 'hour').format('YYYY-MM-DD HH:mm'))
const endTime = ref(dayjs().format('YYYY-MM-DD HH:mm'))
const timeTypeOptions = computed(() => {
  return STORAGE_MODES_OPTIONS.filter(v => [
    STORAGE_MODES.HOUR,
    STORAGE_MODES.DAY,
    STORAGE_MODES.MONTH,
  ].includes(v.value))
})

const isLive = computed(() => unref(timeType) === STORAGE_MODES.NOW)
const isHour = computed(() => unref(timeType) === STORAGE_MODES.HOUR)

const pickerType = computed(() => {
  return ({
    [STORAGE_MODES.NOW]: 'datetime',
    [STORAGE_MODES.FIFTEEN_MINUTES]: 'datetime',
    [STORAGE_MODES.HOUR]: 'datetime',
    [STORAGE_MODES.DAY]: 'date',
    [STORAGE_MODES.MONTH]: 'month',
    [STORAGE_MODES.YEAR]: 'year',
  })[timeType.value] as DatePickType
})
const pickerFormat = computed(() => {
  return ({
    [STORAGE_MODES.NOW]: 'YYYY-MM-DD HH:mm',
    [STORAGE_MODES.FIFTEEN_MINUTES]: 'YYYY-MM-DD HH:mm',
    [STORAGE_MODES.HOUR]: 'YYYY-MM-DD HH',
    [STORAGE_MODES.DAY]: 'YYYY-MM-DD',
    [STORAGE_MODES.MONTH]: 'YYYY-MM',
    [STORAGE_MODES.YEAR]: 'YYYY',
  })[timeType.value]
})

const indicatorDataCurveModalRef = ref<InstanceType<typeof IndicatorDataCurveModal>>()
const indicatorNumber = ref<string>()
async function clickValue(code: string) {
  indicatorNumber.value = code
  await nextTick()
  indicatorDataCurveModalRef.value?.showModal()
}

const {
  loading,
  columns,
  lists,
  getLists,
  pagination,
} = useTemplateData(clickValue)

function handleClickNode(o: TreeNodeData) {
  setCurrent(o)
}

function format(v: string) {
  return dayjs(v).format(
    unref(isLive)
      ? 'YYYY-MM-DD HH:mm:00'
      : unref(pickerFormat),
  )
}

async function clickSearch() {
  if (new Date(unref(startTime)).getTime() > new Date(unref(endTime)).getTime())
    return ElMessage.error('结束时间不能小于开始时间')

  await getTableData()
}

async function getTableData() {
  const modelId = unref(current)?.id
  if (modelId) {
    await getLists({
      timeType: timeType.value,
      modelId: unref(current)?.id,
      startTime: format(startTime.value),
      endTime: format(endTime.value),
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize,
    })
  }
}

async function handleExportData(checkedColumns: any) {
  try {
    const { data } = await exportData({
      timeType: timeType.value,
      modelId: unref(current)?.id,
      startTime: format(startTime.value),
      endTime: format(endTime.value),
      indicatorNumberList: checkedColumns.map((v: any) => v.prop).slice(1),
    })
    if (data?.url) {
      window.open(data.url)
    }
  }
  catch (e) {}
}

async function handleChangeTimeType() {
  const s = unref(startTime)
  const e = unref(endTime)

  startTime.value = ''
  endTime.value = ''
  await nextTick()
  startTime.value = dayjs(s).format(unref(pickerFormat))
  endTime.value = dayjs(e).format(unref(pickerFormat))
}

watch(() => unref(current)?.id, () => {
  clickSearch()
})

onBeforeUnmount(() => {
  setCacheModelId(null)
})
</script>

<template>
  <div class="padding-sm flex gap-4 container">
    <div class="points-container flex-shrink-0">
      <ApplicationModelTree v-if="code" :code="code" @click-node="handleClickNode" />
    </div>
    <div class="flex flex-1 flex-col overflow-auto">
      <TableLists
        :loading="loading"
        :lists="lists"
        :columns="columns"
        show-toolbox
        custom-download
        @download="(checkedColumns: any) => handleExportData(checkedColumns)"
      >
        <template #actions>
          <ElForm class="flex-shrink-0" inline>
            <ElFormItem label="采集时间">
              <ElSelect v-model="timeType" class="free !w-[120px]" @change="handleChangeTimeType">
                <ElOption
                  v-for="item in timeTypeOptions"
                  :key="item.value" :label="item.label" :value="item.value"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="统计时间">
              <ElDatePicker
                v-model="startTime"
                :popper-class="isHour ? 'is-hour-in-hide-panel' : ''"
                :type="pickerType"
                :format="pickerFormat"
                :value-format="pickerFormat"
                :clearable="false"
              />
              <span class="fs-14 text-placeholder mx-3">至</span>
              <ElDatePicker
                v-model="endTime"
                :popper-class="isHour ? 'is-hour-in-hide-panel' : ''"
                :type="pickerType"
                :format="pickerFormat"
                :value-format="pickerFormat"
                :clearable="false"
              />
            </ElFormItem>
            <ElFormItem>
              <SearchButton @click="clickSearch" />
            </ElFormItem>
          </ElForm>
        </template>
      </TableLists>
      <ListsPagination
        v-model:page-num="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        class="self-end"
        :total="pagination.total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>

    <!-- 指标数据折线图 -->
    <IndicatorDataCurveModal
      v-if="indicatorNumber"
      ref="indicatorDataCurveModalRef"
      :indicator-number="indicatorNumber"
    />
  </div>
</template>

<style lang="scss">
.is-hour-in-hide-panel {
  .el-time-panel {
    .el-time-spinner__wrapper {
      width: 100%;
      &:last-child {
        display: none;
      }
    }
  }
}
</style>
